<template>
  <div class="dialog-container">
    <el-tabs v-model="queryParams.type" class="demo-tabs">
      <el-tab-pane label="固定部位分组" name="1"></el-tab-pane>
      <el-tab-pane label="灵活部位分组" name="2"></el-tab-pane>
    </el-tabs>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dispatch:schedulingPlanGrouping:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="small" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dispatch:schedulingPlanGrouping:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dispatch:schedulingPlanGrouping:remove']">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="schedulingPlanGroupingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部位" align="center" prop="departs" />
      <el-table-column label="开始日期" align="center" prop="startDay" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="间隔" align="center" prop="groupInterval" />
      <el-table-column label="间隔周期" align="center" prop="intervalUnit" />
      
      <el-table-column label="轮班方向" align="center" prop="direction" />
      <el-table-column label="轮班数" align="center" prop="directionVector" />
      <el-table-column label="优先级" align="center" prop="priority" />
    </el-table>

    <!-- 添加或修改排班计划分组配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="schedulingPlanGroupingRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="部位" prop="departs">
              <el-checkbox-group v-model="form.departs">
                <el-checkbox v-for="dict in getPlaces" :key="dict.place" :label="dict.place.toString()">
                  {{ '部位' + dict.place + '[' + (dict.direction == 1 ? '上行' : '下行') + ']' }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDay">
              <el-date-picker clearable v-model="form.startDay" type="datetime" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轮班方式" prop="groupType">
              <el-select v-model="form.groupType" placeholder="请选择">
                <el-option v-for="dict in pageConfig.groupTypes" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="form.groupType ==1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="间隔" prop="groupInterval">
                <el-row>
                  <el-col :span="17">
                    <el-input v-model="form.groupInterval" placeholder="请输入间隔" />
                  </el-col>
                  <el-col :span="7">
                    <el-select v-model="form.intervalUnit" placeholder="请选择">
                      <el-option v-for="dict in pageConfig.intervalUnits" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                    </el-select>
                  </el-col>

                </el-row>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="轮班方向" prop="direction">
                <el-select v-model="form.direction" placeholder="请选择">
                  <el-option v-for="dict in pageConfig.directions" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="轮班数" prop="directionVector">
                <el-input v-model="form.directionVector" placeholder="请输入轮班数" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-input v-model="form.priority" placeholder="请输入升序,即:1>2>3....." />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SchedulingPlanGrouping">
import moment from 'moment';
import { listSchedulingPlanGrouping, getSchedulingPlanGrouping, delSchedulingPlanGrouping, addSchedulingPlanGrouping, updateSchedulingPlanGrouping, getPlaceSelectList } from "@/api/dispatch/schedulingPlanGrouping";
import { reactive } from "vue";
const props = defineProps({
  // 当前的值
  planId: [Number, String],
});
const { proxy } = getCurrentInstance();

const schedulingPlanGroupingList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    type: '1'
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    departs: [
      { required: true, message: "部位不能为空", trigger: "blur" }
    ],
    startDay: [
      { required: true, message: "开始日期不能为空", trigger: "blur" }
    ],
    groupType: [
      { required: true, message: "部位分组轮班方式不能为空", trigger: "change" }
    ],
    groupInterval: [
      { required: true, message: "间隔不能为空", trigger: "blur" }
    ],
    direction: [
      { required: true, message: "轮班方向不能为空", trigger: "change" }
    ],
    directionVector: [
      { required: true, message: "轮班数不能为空", trigger: "blur" }
    ],
    priority: [
      { required: true, message: "优先级不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const pageConfig = reactive({
  groupTypes: [{ "label": "自定义", "value": 1 }, { "label": "3天2部位", "value": 2 }],
  intervalUnits: [{ "label": "天", "value": 'day' }, { "label": "月", "value": 'month' }],
  directions: [{ "label": "上日班次增加", "value": 1 }, { "label": "上日班次减少", "value": 2 }],
})

/** 查询排班计划分组配置列表 */
function getList() {
  loading.value = true;
  listSchedulingPlanGrouping(queryParams.value).then(response => {
    schedulingPlanGroupingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    planId: null,
    departs: [],
    type: null,
    startDay: moment().format('YYYY-MM-DD') ,
    groupType: 1,
    groupInterval: 1,
    intervalUnit: 'day',
    direction: null,
    directionVector: 1,
    priority: 1,
    deptId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("schedulingPlanGroupingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加排班计划分组配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getSchedulingPlanGrouping(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    form.value.departs = form.value.departs.split(",");
    open.value = true;
    title.value = "修改排班计划分组配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulingPlanGroupingRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      form.value.departs = form.value.departs.join(",");
      form.value.type = queryParams.value.type;
      form.value.planId = props.planId;
      if (form.value.id != null) {
        updateSchedulingPlanGrouping(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSchedulingPlanGrouping(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除排班计划分组配置编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSchedulingPlanGrouping(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dispatch/schedulingPlanGrouping/export', {
    ...queryParams.value
  }, `schedulingPlanGrouping_${new Date().getTime()}.xlsx`)
}

// getList();
const getPlaces = ref([]);
function getPlacesLists() {
  getPlaceSelectList(props.planId, queryParams.value.type).then(res => {
    getPlaces.value = res.data
  })
}

watch(()=>props, (newQuestion, oldQuestion) => {
  getList()
  getPlacesLists()
}, { immediate: true });

</script>
